package  
{
	import ConfigData;
	import AssetManager;
	import org.flixel.*;
	
	public class MusicManager 
	{
		public var musicTracks:Array = new Array();
		public var currentTrack:int = 0;
		public var nextTrack:int = -1;
		private var _playState:PlayState = null;
		
		public function MusicManager(playState:PlayState)
		{
			_playState = playState;
			musicTracks.push(FlxG.play(AssetManager.AdultMusic, 0.0, true));
			musicTracks.push(FlxG.play(AssetManager.AdultBabyMusic, 0.0, true));
			musicTracks.push(FlxG.play(AssetManager.AdultToddlerMusic, 0.0, true));
			musicTracks.push(FlxG.play(AssetManager.AdultTeenMusic, 0.0, true));
			musicTracks.push(FlxG.play(AssetManager.AdultAdultMusic, 0.0, true));
			musicTracks.push(FlxG.play(AssetManager.OldAdultMusic, 0.0, true));
			musicTracks.push(FlxG.play(AssetManager.InvalidAdultMusic, 0.0, true));
		}
		public function update():void 
		{
			if (_playState.doingWin)
			{
				for (var m:int = 0; m < musicTracks.length; m++)
				{
					if (musicTracks[m].volume > 0)
					{
						musicTracks[m].volume -= FlxG.elapsed;
					}
				}
				return;
			}
			// First, zero out both volumes, in case we're all dead or current or next track changes
			musicTracks[currentTrack].volume = 0;
			if (nextTrack >= 0 && nextTrack < 7)
			{
				musicTracks[nextTrack].volume = 0;
			}
			// Find the youngest human (look to the future right?)
			var youngestHuman:Human = _playState.getYoungestHuman();
			if (youngestHuman == null) {
				// Crap, no one is alive, return (we've already set volumes to 0 after all)
				return;
			}
			// Let's pretend we're all current track!
			var percentageCurrentTrack:Number = 1.0;
			// Get the current track based on age of youngest human
			currentTrack = Math.floor(youngestHuman.getAge());
			// You know what the next track would be
			nextTrack = currentTrack + 1;
			percentageCurrentTrack = 1.0 - (youngestHuman.getAge() - Math.floor(youngestHuman.getAge()));
			// Set volumes baby!
			musicTracks[currentTrack].volume = percentageCurrentTrack;
			if (nextTrack >= 0 && nextTrack < 7)
			{
				musicTracks[nextTrack].volume = 1.0 - percentageCurrentTrack;
			}
		}
	}

}